<template>
  <div class="LeftTree border_right_base" v-loading="TreeLoading">
    <vxe-toolbar class="border_bottom_base">
      <template #buttons>
        <vxe-button v-show="!isShowSearch" size="mini" @click="setAllTreeExpand">展开所有节点
        </vxe-button>
        <vxe-button v-show="!isShowSearch" size="mini" @click="clearTreeExpand">关闭所有节点</vxe-button>
        <vxe-input
          size="mini"
          style="width: 208px"
          v-show="isShowSearch"
          v-model="tableTree.filInput"
          placeholder="输入分组名过滤"
        ></vxe-input>
        <vxe-button size="mini" @click="isShowSearch = !isShowSearch"
        ><i class="vxe-icon-search c_pointer"></i>
        </vxe-button>
      </template>
    </vxe-toolbar>
    <div class="wrap_table">
      <vxe-table
        ref="VxeTreeTable"
        :data="tableTree.filTreeData"
        show-overflow
        height="auto"
        border="none"
        :show-header="false"
        :row-config="{ height: 38, isCurrent: true, isHover: true }"
        :tree-config="{
          children: 'children',
          iconOpen: 'vxe-icon-square-minus',
          iconClose: 'vxe-icon-square-plus',
          expandAll: true,
          reserve: true
          // transform  使用 flgTreeData ChildrenToParentData() 转化后才能使用
          // transform: true,
        }"
        @cell-click="cellClick"
        @cell-mouseenter="cellMouseEnter"
        @cell-mouseleave="cellMouseLeave"
      >
        <vxe-table-column field="name" width="100%" title="全部数据" tree-node>
          <template #default="{ row }">
            <Icon :type="$refs['VxeTreeTable'].isTreeExpandByRow(row)? 'ios-folder-open' : 'ios-folder'" />
            {{ row.name }}
            <span class="more-action" v-show="(row.id ===tableTree.showMoreId) && row.edit === 'true'">
                  <i class="iconfont i-zengjiatianjiajiahao f-s-16 m-r-5" @click="groupAction('create',row)"></i>
                  <i class="iconfont i-bianji f-s-16 m-r-5" @click="groupAction('edit',row)"></i>
                  <i class="iconfont i-shanchu2 f-s-16 m-r-5" @click="groupAction('delete',row)"></i>
                </span>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
    <Modal
      width="430px"
      :title="tableTree.groupForm.type === 'create' ? '新建分组': tableTree.groupForm.type === 'edit' ? '编辑分组' : '删除分组' "
      v-model="tableTree.groupModal"
      @on-ok="groupActionOk"
      class-name="vertical-center-modal">
      <div v-if="tableTree.groupForm.type !== 'delete'">
        <Form ref="groupForm" :model="tableTree.groupForm" :hide-required-mark="true" label-position="left"
              :label-width="100" :rules="tableTree.ruleGroup">
          <FormItem :label="tableTree.groupForm.type === 'create' ? '父级分组' : '移动到的分组'" prop="parentId">
            <Poptip placement="bottom" v-model="tableTree.isShowBaseTree">
              <Input style="width: 280px" v-model="tableTree.groupForm.parent_group_name" icon="md-arrow-dropdown"
                     placeholder="parentId" readonly></Input>
              <template #content>
                <div style="width: 280px">
                  <base-tree
                    :tree-data="tableTree.groupForm.type === 'create' ? tableTree.treeData : tableTree.editTreeData "
                    @getBaseTreeCurrentChange="getBaseTreeCurrentChange"></base-tree>
                </div>
              </template>
            </Poptip>
          </FormItem>
          <FormItem label="分组名称" prop="name">
            <Input style="width: 280px" v-model="tableTree.groupForm.name" placeholder="name"></Input>
          </FormItem>
        </Form>
      </div>
      <div v-else>删除后无法恢复，确定要删除分组？</div>
      <template #footer>
        <Button @click="groupActionCancel">取消</Button>
        <Button type="primary" @click="groupActionOk">确认</Button>
      </template>
    </Modal>
  </div>
</template>

<script>
import { httpRequest } from "@/untils/httpRequest";
import BaseTree from "@/views/VxeTree/components/BaseTree";

export default {
  name: "NavTree",
  components: { BaseTree },
  data() {
    return {
      isShowSearch: false,
      TreeLoading: false,
      tableTree: {
        filInput: "",
        showMoreId: 0,
        treeData: [],
        filTreeData: [],
        parentTreeData: [],
        editTreeData: [],
        popoverRefs: {},
        groupModal: false,
        isShowBaseTree: false,
        groupForm: {
          type: "create",
          parentId: null,
          name: "",
          id: null,
          parent_group_name: ""
        },
        ruleGroup: {
          name: [{ required: true, message: "分组名称不能为空", trigger: "blur" }],
          parent_group_name: [{ required: true, message: "目标分组不能为空", trigger: "blur" }]
        },
        selectRow: {}
      }
    };
  },
  methods: {
    //1. 获取tree数据(直接返回的是带children的层级结构) --- 暂时不用
    getTreeData(type) {
      return new Promise((resolve) => {
        // this.TreeLoading = true;
        httpRequest("post", "/component/getTreeData", null, null, "proxy").then((res) => {
          this.addExtraParameter(res.data.data, null, null, null, null);
          this.tableTree.parentTreeData = this.ChildrenToParentData(res.data.data, null, null);
          this.tableTree.treeData = res.data.data;
          this.tableTree.filTreeData = res.data.data;
          if (type === "edit") {
            let current_position = this.tableTree.selectRow.current_position.replace("value", "this.tableTree.filTreeData");
            this.$refs["VxeTreeTable"].setCurrentRow(eval(current_position));
          } else {
            this.$refs["VxeTreeTable"].setCurrentRow(this.tableTree.filTreeData[0]);
          }
          this.TreeLoading = false;
          resolve();
        });
      });
    },
    //1. 带children的层级结构转化带parentId的数组 --- 暂时不用
    ChildrenToParentData(dataSource, newId, result) {
      var _this = this;
      if (!result) {
        result = [];
      }
      dataSource.map(function(item) {
        if (item.type === "outer") {
          item.parentId = null;
        } else if (newId) {
          item.parentId = newId;
        }
        result.push(item);
        if (item.children.length > 0) {
          item.children.map(function(sonItem) {
            sonItem.parentId = item.id;
            result.push(sonItem);
            if (sonItem.children.length > 0) {
              _this.ChildrenToParentData(sonItem.children, sonItem.id, result);
            }
          });
        }
      });
      return result;
    },
    //2. 获取tree数据(返回的是从数据库里获取的parentId的数组)
    getParentIdTreeData(type) {
      return new Promise((resolve) => {
        this.TreeLoading = true;
        httpRequest("post", "/component/getParentIdTreeData", null, null, "proxy")
          .then((res) => {
            let flg = this.ParentToChildrenData(res.data.data);
            this.addExtraParameter(flg, null, null, null, null);
            this.tableTree.parentTreeData = flg;
            this.tableTree.treeData = flg;
            this.tableTree.filTreeData = flg;
            if (type === "edit") {
              let current_position = this.tableTree.selectRow.current_position.replace("value", "this.tableTree.filTreeData");
              this.$refs["VxeTreeTable"].setCurrentRow(eval(current_position));
            } else {
              this.$refs["VxeTreeTable"].setCurrentRow(this.tableTree.filTreeData[0]);
            }
            this.TreeLoading = false;
            resolve(type);
          })
          .finally(() => {
            this.TreeLoading = false;
            this.tableTree.selectRow = this.currentHighLight();
          });
      });
    },
    //2. 带有parentId的数组转化为带children的层级结构
    ParentToChildrenData(dataSource) {
      let del = [];
      dataSource.forEach((el) => {
        el.children = [];
        dataSource.forEach((item) => {
          if (item.parentId == el.id) {
            el.children.push(item);
            del.push(item.id); // 删除那些要推进列表中的即可这些是重复的item删除
          }
        });
      });
      // 过滤那些已经push到el.children中的
      return dataSource.filter((item) => !del.includes(item.id));
    },
    //3. 数据添加额外的参数
    addExtraParameter(dataSource, parent_group_id, parent_group_name, current_level, current_position) {
      if (!parent_group_id) {
        parent_group_id = null;
        parent_group_name = null;
        current_level = 1;
        current_position = "value";
      }
      dataSource.map((item, index) => {
        item.parent_group_id = parent_group_id;
        item.parent_group_name = parent_group_name;
        item.current_level = current_level;
        item.current_position = current_position + "[" + index + "]";
        this.addExtraParameter(
          item.children,
          item.id,
          item.name,
          item.current_level + 1,
          current_position + "[" + index + "]" + ".children"
        );
      });
    },
    //4. 过滤树（针对的是带children的层级结构）
    filterTree(dataSource, query, isParent) {
      if (!(dataSource && dataSource.length)) {
        return [];
      }
      let resultTreeData = [];
      let hasName = function(item) {
        return !!item.name.includes(query);
      };
      dataSource.map((item) => {
        if (isParent) {
          //一、带父节点
          // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
          // 2. 自己本身符合条件
          let subs = this.filterTree(item.children, query, isParent);
          if (hasName(item)) {
            resultTreeData.push(item);
          } else if (subs && subs.length) {
            item.children = subs;
            resultTreeData.push(item);
          }
        } else {
          //二、不带父节点
          if (hasName(item)) {
            resultTreeData.push(item);
            item.children = this.filterTree(item.children, query, isParent);
          } else {
            resultTreeData.push(...this.filterTree(item.children, query, isParent));
          }
        }
      });
      return resultTreeData.length ? resultTreeData : [];
    },
    //5. 编辑分组不能移动到自己或自己的子级下
    EditTreeData(treeData, parent_group_id, id) {
      treeData.map((item) => {
        if (item.id === parent_group_id) {
          item.children.map((sonItem, index) => {
            if (sonItem.id === id) {
              item.children.splice(index, 1);
            }
          });
        } else {
          this.EditTreeData(item.children, parent_group_id, id);
        }
      });
      return treeData;
    },
    //6. 删除某一个层级节点，其子节点均被删除
    findChildrenIdByParentId(tableTree, id, deleteIds) {
      if (!deleteIds) {
        deleteIds = [id];
      }
      tableTree.map((item) => {
        if (item.parentId === id) {
          deleteIds.push(item.id);
          if (item.children.length > 0) {
            this.findChildrenIdByParentId(item.children, item.id, deleteIds);
          }
        } else {
          if (item.children.length > 0) {
            this.findChildrenIdByParentId(item.children, id, deleteIds);
          }
        }
      });
      return deleteIds;
    },
    // 点击触发
    cellClick({ row }) {
      this.tableTree.selectRow = row;
    },
    // 鼠标移入
    cellMouseEnter({ row }) {
      this.tableTree.showMoreId = row.id;
    },
    // 鼠标移除
    cellMouseLeave() {
      this.tableTree.showMoreId = 0;
    },
    // 动态设置遍历的ref
    setPopoverRefs(el, id) {
      this.tableTree.popoverRefs[id] = el;
    },
    // 选择基础树下拉的内容
    getBaseTreeCurrentChange(value) {
      this.tableTree.groupForm.parentId = value.id;
      this.tableTree.groupForm.parent_group_name = value.name;
      this.tableTree.isShowBaseTree = false;
    },
    // 新建/编辑/删除分组
    groupAction(actionType, row) {
      if (row.current_level > 5 && actionType === "create") {
        this.$message.warning("分组层数超过5层，无法新建");
        return;
      }
      this.tableTree.groupModal = true;
      this.tableTree.groupForm.type = actionType;
      this.tableTree.groupForm.parentId =
        actionType === "create" ? row.id : row.parent_group_id;
      this.tableTree.groupForm.parent_group_name =
        actionType === "create" ? row.name : row.parent_group_name;
      this.tableTree.groupForm.id = actionType === "create" ? null : row.id;
      this.tableTree.groupForm.name = actionType === "create" ? "" : row.name;
      this.tableTree.editTreeData =
        actionType === "create"
          ? []
          : this.EditTreeData(
          JSON.parse(JSON.stringify(this.tableTree.treeData)),
          row.parent_group_id,
          row.id
          );
    },
    // 操作确认
    groupActionOk() {
      if (this.tableTree.groupForm.type === "delete") {
        var deleteIds = this.findChildrenIdByParentId(
          this.tableTree.treeData,
          this.tableTree.groupForm.id,
          null
        );
        let params = {
          ids: deleteIds,
          actionType: this.tableTree.groupForm.type
        };
        httpRequest(
          "post",
          "/component/addEditDeleteGroup",
          null,
          params,
          "proxy"
        ).then(() => {
          this.reFresh(params.actionType);
          this.groupActionCancel();
        });
      } else {
        this.$refs["groupForm"].validate((vaild) => {
          if (vaild) {
            let params = {
              id: this.tableTree.groupForm.id,
              name: this.tableTree.groupForm.name,
              parentId: this.tableTree.groupForm.parentId,
              actionType: this.tableTree.groupForm.type
            };
            httpRequest(
              "post",
              "/component/addEditDeleteGroup",
              null,
              params,
              "proxy"
            ).then(() => {
              this.reFresh(params.actionType);
              this.groupActionCancel();
              this.tableTree.groupModal = false;
            });
          } else {
            this.$message.error("请检查表单内容是否符合要求");
          }
        });
      }
    },
    // 操作取消
    groupActionCancel() {
      if (this.tableTree.groupForm.type !== "delete") {
        this.$refs["groupForm"].resetFields();
      }
      this.groupActionReset();
      this.tableTree.groupModal = false;
    },
    // 重置操作
    groupActionReset() {
      this.tableTree.groupForm = {
        type: "create",
        parentId: null,
        name: "",
        id: null,
        parent_group_name: ""
      };
    },
    // 展开
    setAllTreeExpand() {
      this.$refs["VxeTreeTable"].setAllTreeExpand(true);
    },
    // 关闭
    clearTreeExpand() {
      this.$refs["VxeTreeTable"].clearTreeExpand(true);
    },
    // 刷新
    reFresh(type) {
      this.getParentIdTreeData(type).then(() => {
        this.setAllTreeExpand();
      });
    },
    // 当前高亮行
    currentHighLight() {
      // if ()
      return this.$refs["VxeTreeTable"].getCurrentRecord();
    }
  },
  watch: {
    // 搜索框显隐
    isShowSearch() {
      this.tableTree.filInput = "";
    },
    // 输入框内容改变
    "tableTree.filInput": {
      handler(value) {
        if (value === '') {
          this.tableTree.filTreeData = JSON.parse(
            JSON.stringify(this.tableTree.treeData)
          );
        } else {
          this.tableTree.filTreeData = this.filterTree(
            JSON.parse(JSON.stringify(this.tableTree.treeData)),
            value,
            true
          );
        }
      }
    },
    "tableTree.selectRow": {
      immediate: true, deep: true,
      handler(value) {
        this.$emit("selectRow", value);
      }
    }
  },
  mounted() {
    this.getParentIdTreeData(null);
  }
};
</script>

<style scoped lang="less">
.LeftTree {
  width: 100%;
  height: 100%;
  overflow: auto;

  .border_bottom_base {
    padding-left: 10px;
  }

  .wrap_table {
    height: calc(100% - 46px);

    .more-action {
      position: absolute;
      right: -10px;
      top: 2px;
      cursor: pointer;
    }
  }
}
</style>
<style lang="less">
.left_tree_popover {
  position: absolute;
  background: #FFF;
  min-width: 50px !important;
  border: 1px solid #EBEEF5;
  padding: 12px;
  z-index: 2000;
  color: #606266;
  line-height: 0;
  text-align: justify;
  font-size: 14px;
  -webkit-box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  word-break: break-all;

  .group_action {
    display: inline-block;
    width: 100%;
    height: 30px;
    line-height: 30px;

    &:hover {
      background-color: #b4ebff;
    }
  }
}
</style>